import { ctrlMgr } from "../Manager/CtrlMgr";
import { loadingMgr } from "../Manager/LoadingMgr";
import { logMgr } from "../Manager/LogMgr";
import { timerMgr } from "../Manager/TimerMgr";
import { toastMgr } from "../Manager/ToastMgr";
import { viewMgr } from "../Manager/ViewMgr";

const { ccclass, property } = cc._decorator;

@ccclass
export abstract class BaseScene extends cc.Component {

    abstract onSceneStart(): void

    onLoad() {
        let cvs = cc.find('Canvas')
        this.resizeWindow(cvs)

        viewMgr.initRoot(this.node)
        toastMgr.initRoot(this.node)
        loadingMgr.initRoot(this.node)
        timerMgr.init()

        cc.game.on(cc.game.EVENT_HIDE, this.onBackground, this)
        cc.game.on(cc.game.EVENT_SHOW, this.onForeground, this)

        this.onSceneStart()
    }

    protected onDestroy(): void {
        viewMgr.clearAll()
        toastMgr.dispose()
        loadingMgr.dispose()
        cc.game.off(cc.game.EVENT_HIDE, this.onBackground, this)
        cc.game.off(cc.game.EVENT_SHOW, this.onForeground, this)
        super.onDestroy()
    }

    /**
    * 调整canvas大小适配屏幕
    */
    resizeWindow(cvsNode: cc.Node) {
        var cvs = cvsNode.getComponent(cc.Canvas);
        var dr = cvs.designResolution;
        var s = cc.view.getFrameSize();
        var rw = s.width;
        var rh = s.height;
        var finalW = rw;
        var finalH = rh;
        if ((rw / rh) > (dr.width / dr.height)) {
            finalH = dr.height;
            finalW = finalH * rw / rh;
        }
        else {
            finalW = dr.width;
            finalH = rh / rw * finalW;
        }
        cvs.designResolution = cc.size(finalW, finalH);
        cvs.node.width = finalW;
        cvs.node.height = finalH;
        cc.log(`designResolution Frame ${s.width}X${s.height}`)
        cc.log(`designResolution ${finalW}X${finalH}`)
        cvs.node.emit('resize');
    }

    protected onBackground() {
        logMgr.log("onBackground")
        ctrlMgr.onBackground()
    }

    protected onForeground() {
        logMgr.log("onForeground")
        ctrlMgr.onForeground()
    }
}
